// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化周次选择框 (1-25周)
    const weekSelect = document.getElementById('week');
    for (let i = 1; i <= 25; i++) {
        const option = document.createElement('option');
        option.value = i;
        option.textContent = `第${i}周`;
        weekSelect.appendChild(option);
    }

    // 初始化节次选择框 (1-12节)
    const startClassSelect = document.getElementById('startClass');
    const endClassSelect = document.getElementById('endClass');
    for (let i = 1; i <= 12; i++) {
        const option1 = document.createElement('option');
        option1.value = i;
        option1.textContent = `第${i}节`;
        startClassSelect.appendChild(option1);

        const option2 = document.createElement('option');
        option2.value = i;
        option2.textContent = `第${i}节`;
        endClassSelect.appendChild(option2);
    }

    // 设置默认结束节次为第2节
    endClassSelect.value = 2;

    // 绑定查询按钮事件
    document.getElementById('queryBtn').addEventListener('click', queryFreeStudents);
});

// 查询空闲学生
async function queryFreeStudents() {
    const folderInput = document.getElementById('folderInput');
    const week = document.getElementById('week').value;
    const day = document.getElementById('day').value;
    const startClass = document.getElementById('startClass').value;
    const endClass = document.getElementById('endClass').value;
    const freeStudentsDiv = document.getElementById('freeStudents');
    const busyStudentsDiv = document.getElementById('busyStudents');
    const loadingDiv = document.getElementById('loading');

    // 检查是否选择了文件夹
    if (!folderInput.files || folderInput.files.length === 0) {
        alert('请先选择包含课表的文件夹');
        return;
    }

    // 显示加载状态
    loadingDiv.classList.remove('hidden');
    freeStudentsDiv.innerHTML = '';
    busyStudentsDiv.innerHTML = '';

    try {
        // 获取所有xls文件
        const xlsFiles = Array.from(folderInput.files).filter(file => 
            file.name.endsWith('.xls') && !file.name.includes('pdf')
        );

        if (xlsFiles.length === 0) {
            throw new Error('所选文件夹中没有找到.xls文件');
        }

        const freeStudents = [];
        const busyStudents = [];

        // 遍历所有xls文件
        for (const file of xlsFiles) {
            try {
                const result = await checkIfFreeAndGetStudentName(file, week, day, startClass, endClass);
                if (result.isFree) {
                    freeStudents.push(result.studentName);
                } else {
                    busyStudents.push(result.studentName);
                }
            } catch (error) {
                console.error(`处理文件 ${file.name} 时出错:`, error);
            }
        }

        // 显示结果
        displayFreeStudents(freeStudents);
        displayBusyStudents(busyStudents);
    } catch (error) {
        console.error('查询过程中出错:', error);
        freeStudentsDiv.innerHTML = `<p style="color: red;">查询出错: ${error.message}</p>`;
    } finally {
        // 隐藏加载状态
        loadingDiv.classList.add('hidden');
    }
}

// 检查学生在指定时间是否空闲并获取学生姓名
function checkIfFreeAndGetStudentName(file, week, day, startClass, endClass) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        
        reader.onload = function(e) {
            try {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, { type: 'array' });
                
                // 获取第一个工作表
                const firstSheetName = workbook.SheetNames[0];
                const worksheet = workbook.Sheets[firstSheetName];
                
                // 从第一行合并单元格中提取学生姓名 (A1-G1)
                let studentName = '未知学生';
                const nameCell = worksheet['A1'];
                if (nameCell && nameCell.v) {
                    const nameText = nameCell.v;
                    // 格式为"武汉科技大学 XXX 学生个人课表"
                    const match = nameText.match(/武汉科技大学\s*(.+?)\s*学生个人课表/);
                    if (match && match[1]) {
                        studentName = match[1];
                    } else {
                       studentName = null;
                    }
                } else{
                    studentName = null;
                }
                
                // 根据星期几确定要检查的列 (B=星期一, C=星期二, ..., H=星期日)
                // 星期一是B列，对应索引1，所以需要将星期值转换为列字母
                const column = String.fromCharCode(65 + parseInt(day)); // 66='B'(星期一), 67='C'(星期二), ...
                
                // 检查指定节次范围内的课程情况
                let isFree = true;
                
                // 计算要检查的行范围
                // 第1-2节在第4行，第3-4节在第5行，...，第11-12节在第9行
                // 所以第n节课所在的行数为：Math.ceil(n/2) + 3
                const startRow = Math.ceil(parseInt(startClass)/2) + 3;
                const endRow = Math.ceil(parseInt(endClass)/2) + 3;
                
                // 检查[startRow, endRow]范围内的所有行
                for (let row = startRow; row <= endRow; row++) {
                    const cellRef = column + row;
                    const cell = worksheet[cellRef];
                    
                    // 如果单元格存在且有值，则表示该时间有课
                    if (cell && cell.v) {
                        const cellText = String(cell.v).trim();
                        // console.log(cellText);
                        if (cellText !== "") {
                            // 解析单元格中的课程信息，可能包含多个课程
                            const courses = parseCourseCell(cellText);
                            const currentWeek = parseInt(week);
                            
                            // 检查任意一门课程是否在当前周
                            for (const course of courses) {
                                if (isWeekInCourse(course.weekInfo, currentWeek)) {
                                    isFree = false;
                                    break;
                                }
                            }
                            
                            if (!isFree) {
                                break;
                            }
                        }
                    }
                }
                
                resolve({
                    isFree: isFree,
                    studentName: studentName
                });
            } catch (error) {
                reject(error);
            }
        };
        
        reader.onerror = function() {
            reject(new Error('读取文件失败'));
        };
        
        reader.readAsArrayBuffer(file);
    });
}

// 解析单元格中的课程信息
function parseCourseCell(cellText) {
    const courses = [];
    const lines = cellText.split('\n');
    
    // 按课程分组解析，每5行为一组课程信息,加上后面的空白行，一共6行
    for (let i = 0; i < lines.length; i += 6) {
        if (i + 4 < lines.length) {
            const course = {
                name: lines[i].trim(),
                teacher: lines[i + 1].trim(),
                weekInfo: lines[i + 2].trim(),
                location: lines[i + 3].trim(),
                classTime: lines[i + 4].trim()
            };
            courses.push(course);
        }
    }
    console.log(courses);
    
    return courses;
}

// 检查指定周次是否在课程的周次信息中
function isWeekInCourse(weekInfo, week) {
    // 移除"[周]"后缀
    const weekStr = weekInfo.replace(/\[周\]$/, '');
    
    // 分割逗号分隔的不同周次段
    const weekParts = weekStr.split(',');
    
    for (const part of weekParts) {
        if (part.includes('-')) {
            // 处理范围格式如"7-8"
            const [start, end] = part.split('-').map(Number);
            if (week >= start && week <= end) {
                return true;
            }
        } else {
            // 处理单独的周次如"16"
            const singleWeek = Number(part);
            if (week === singleWeek) {
                return true;
            }
        }
    }
    
    return false;
}

// 显示空闲学生列表
function displayFreeStudents(students) {
    const freeStudentsDiv = document.getElementById('freeStudents');
    
    if (students.length === 0) {
        freeStudentsDiv.innerHTML = '<p>没有找到空闲的学生</p>';
        return;
    }
    
    const studentCount = document.createElement('div');
    studentCount.className = 'student-count';
    studentCount.textContent = `共有 ${students.length} 名空闲学生：`;
    
    const studentList = document.createElement('ul');
    studentList.className = 'free-student-list';
    
    students.forEach(student => {
        const listItem = document.createElement('li');
        listItem.textContent = student;
        studentList.appendChild(listItem);
    });
    
    freeStudentsDiv.innerHTML = '';
    freeStudentsDiv.appendChild(studentCount);
    freeStudentsDiv.appendChild(studentList);
}

// 显示有课学生列表
function displayBusyStudents(students) {
    const busyStudentsDiv = document.getElementById('busyStudents');
    
    if (students.length === 0) {
        busyStudentsDiv.innerHTML = '<p>没有找到有课的学生</p>';
        return;
    }
    
    const studentCount = document.createElement('div');
    studentCount.className = 'student-count';
    studentCount.textContent = `共有 ${students.length} 名有课学生：`;
    
    const studentList = document.createElement('ul');
    studentList.className = 'busy-student-list'; // 使用专门的样式类
    
    students.forEach(student => {
        const listItem = document.createElement('li');
        listItem.textContent = student;
        studentList.appendChild(listItem);
    });
    
    busyStudentsDiv.innerHTML = '';
    busyStudentsDiv.appendChild(studentCount);
    busyStudentsDiv.appendChild(studentList);
}
